package com.ruoyi.order.controller;

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.reflect.TypeToken;
import com.ruoyi.classrecords.domain.ClassRecords;
import com.ruoyi.classrecords.service.IClassRecordsService;
import com.ruoyi.coursestatistics.domain.DzCourseStatistics;
import com.ruoyi.coursestatistics.service.IDzCourseStatisticsService;
import com.ruoyi.order.domain.Order;
import com.ruoyi.order.domain.OrderOtherAdd;
import com.ruoyi.orderdeduct.domain.OrderDeduct;
import com.ruoyi.orderdeduct.service.IOrderDeductService;
import com.ruoyi.ordersale.domain.OrderSale;
import com.ruoyi.ordersale.service.IOrderSaleService;
import com.ruoyi.scheduling.domain.DzCourseScheduling;
import com.ruoyi.scheduling.service.IDzCourseSchedulingService;
import com.ruoyi.student.domain.DzStudent;
import com.ruoyi.student.service.IDzStudentService;
import com.ruoyi.utils.JSONUtils;
import com.ruoyi.withholdingfees.domain.WithholdingFees;
import com.ruoyi.withholdingfees.service.IWithholdingFeesService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.order.service.IOrderService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 订单
 * Controller
 *
 * @author ruoyi
 * @date 2024-01-11
 */
@RestController
@RequestMapping("/order/order")
public class OrderController extends BaseController {
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IOrderSaleService orderSaleService;

    @Autowired
    private IDzStudentService dzStudentService;

    @Autowired
    private IDzCourseStatisticsService dzCourseStatisticsService;

    /**
     * 查询订单
     * 列表
     */
    @PreAuthorize("@ss.hasPermi('order:order:list')")
    @GetMapping("/list")
    public TableDataInfo list(Order order) {
        startPage();
        List<Order> list = orderService.selectOrderList(order);
        return getDataTable(list);
    }

    @GetMapping("/ListByCourse")
    public TableDataInfo selectOrderListByCourse(Order order) {
//        startPage();
        List<Order> list = orderService.selectOrderListByCourse(order);
        return getDataTable(list);
    }


    /**
     * 导出订单
     * 列表
     */
    @PreAuthorize("@ss.hasPermi('order:order:export')")
    @Log(title = "订单", businessType = BusinessType.EXPORT)

    @PostMapping("/export")
    public void export(HttpServletResponse response, Order order) {
        List<Order> list = orderService.selectOrderList(order);
        ExcelUtil<Order> util = new ExcelUtil<Order>(Order.class);
        util.exportExcel(response, list, "订单数据");

    }

    /**
     * 获取订单
     * 详细信息
     */
    @PreAuthorize("@ss.hasPermi('order:order:query')")
    @GetMapping(value = "/{orderId}")
    public AjaxResult getInfo(@PathVariable("orderId") Long orderId) {
        return success(orderService.selectOrderByOrderId(orderId));
    }

    int yuanlai;

    /**
     * 新增订单
     */
    @PreAuthorize("@ss.hasPermi('order:order:add')")
    @Log(title = "订单", businessType = BusinessType.INSERT)

    @PostMapping
    public AjaxResult add(@RequestBody Order order) throws ParseException {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String today = sdf.format(date);
        int code = (int) (Math.random() * 900000) + 100000;
        order.setOrderRemark2(today + code);
        orderService.insertOrder(order);
        Long orderId = order.getOrderId();
        //机构ID
        String dept_id = order.getDeptId();
        String OrderCourse = order.getOrderCourse();
        String orderStudentName = order.getOrderStudentName();
//        String unitPrice = order.getUnitPrice();


        //新增订单，添加到订单销售表
        //获取比例信息
        String order5 = order.getSaleJson();
        if (order5 != null || order5 != "") {
            //获取总金额
            String allmoney = order.getMoneyOrderTotal();
            Type type = new TypeToken<ArrayList<OrderOtherAdd>>() {
            }.getType();
            //订单销售表插入
            ArrayList<OrderOtherAdd> list = JSONUtils.parseJSONArray(order5, type);
            System.out.println(list);
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    String proportion = list.get(i).getUsernumber();
                    String teacher = list.get(i).getUser();
                    int salemoney = Integer.parseInt(allmoney) * Integer.parseInt(proportion) / 100;
                    System.out.println(allmoney);
                    System.out.println(proportion);
                    System.out.println(salemoney);
                    OrderSale orderSale = new OrderSale();
                    orderSale.setOrderSaleAllmoney("" + allmoney);
                    orderSale.setOrderSaleProportion(proportion);
                    orderSale.setOrderSaleMoney("" + salemoney);
                    orderSale.setOrderSaleTeacher(teacher);
                    orderSale.setDeptId(order.getDeptId());
                    orderSale.setOrderId("" + orderId);
                    orderSaleService.insertOrderSale(orderSale);

                }
            }


        }
        String studentid = order.getStudentId();

        Order orderquery = new Order();
        orderquery.setStudentId(studentid);
        orderquery.setOrderRemark10("0");

        List<Order> Orderlist = orderService.selectOrderList(orderquery);
        int value = 0;
        for (int w = 0; w < Orderlist.size(); w++) {
            String residue1 = Orderlist.get(w).getResidue();
            int intresidue1 = Integer.parseInt(residue1);
            //剩余课数量
            value = value + intresidue1;


        }
        //更新用户信息
        DzStudent dzStudent2 = dzStudentService.selectDzStudentById(Long.parseLong(order.getStudentId()));
        dzStudent2.setRemainingClassHours("" + value);
        dzStudentService.updateDzStudent(dzStudent2);


        return toAjax(true);
    }

    /**
     * 修改订单
     */
    @PreAuthorize("@ss.hasPermi('order:order:edit')")
    @Log(title = "订单", businessType = BusinessType.UPDATE)

    @PutMapping
    public AjaxResult edit(@RequestBody Order order) {
        return toAjax(orderService.updateOrder(order));
    }

    /**
     * 删除订单
     */
    @PreAuthorize("@ss.hasPermi('order:order:remove')")
    @Log(title = "订单", businessType = BusinessType.DELETE)

    @DeleteMapping("/{orderIds}")
    public AjaxResult remove(@PathVariable Long orderIds) {

        Order order = orderService.selectOrderByOrderId(orderIds);
        String studentid = order.getStudentId();

        Order orderquery = new Order();
        orderquery.setStudentId(studentid);
        orderquery.setOrderRemark10("0");


        orderService.deleteOrderByOrderId(orderIds);


        List<Order> Orderlist = orderService.selectOrderList(orderquery);

        int value = 0;
        for (int w = 0; w < Orderlist.size(); w++) {
            String residue1 = Orderlist.get(w).getResidue();
            int intresidue1 = Integer.parseInt(residue1);
            //剩余课数量
            value = value + intresidue1;


        }
        //更新用户信息
        DzStudent dzStudent = dzStudentService.selectDzStudentById(Long.parseLong(studentid));
        dzStudent.setRemainingClassHours("" + value);

        return toAjax(dzStudentService.updateDzStudent(dzStudent));
    }


    @Autowired
    private IWithholdingFeesService withholdingFeesService;


    @Autowired
    private IOrderDeductService orderDeductService;
    @Autowired
    private IClassRecordsService classRecordsService;
    @Autowired
    public IDzCourseSchedulingService dzCourseSchedulingService;




}
